import 'package:flutter/material.dart';
import 'package:wu_you/data/cache/login_cache.dart';
import 'package:wu_you/utils/string_utils.dart';
import 'package:webview_flutter/webview_flutter.dart';

class NavigatorUtil {

  ///通过页面对象路由
  static Future<T> navigateToPage<T extends Object>(
      BuildContext context, Widget page,
      {bool showLogin}) async {
    if (showLogin == null) {
      bool state = await LoginCache().get();
      if (state == null) {
        state = false;
      }
      if (!state) {
        // return Navigator.push(
        //     context,
        //     MaterialPageRoute(
        //         fullscreenDialog: true, builder: (context) => LoginPage()));
      }
    }
    return Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) {
          return page;
        },
      ),
    );
  }

  ///通过名称路由
  static Future<T> navigateToNamed<T extends Object>(
      BuildContext context, String routeName,
      {bool showLogin}) async {
    if (showLogin == null) {
      bool state = await LoginCache().get();
      if (state == null) {
        state = false;
      }
      if (!state) {
        // return Navigator.push(
        //     context,
        //     MaterialPageRoute(
        //         fullscreenDialog: true, builder: (context) => LoginPage()));
      }
    }
    // List<String> routes = routeName.split("?");
    // if (routes.length >= 2) {
    //   return Navigator.pushNamed<T>(context, routes.first,
    //       arguments: routes.last);
    // }
    // return Navigator.pushNamed<T>(context, routes.first);

    List<String> routes = routeName.split("?");
    Uri uri = Uri.parse(routeName);
    if (routes.length >= 2) {
      String arg = StringUtils.toJsonStr(uri.queryParameters);
      if(routes.first.contains("mall/product") || routes.first.contains("home/college") || routes.first.contains("mall/order")){
        String mallArg = uri.queryParameters.keys.first;
        return Navigator.pushNamed<T>(context, routes.first,arguments: mallArg);
      }
      return Navigator.pushNamed<T>(context, routes.first,arguments: arg);
    }
    return Navigator.pushNamed<T>(context, routes.first);
  }

  ///A->B->C->D路由到其中BC任意页面并移除其中部分页面，移除规则由predicate
  ///若predicate为空则相当于从首页重新打开B页面
  ///适用于从D->B需要刷新数据的情况
  static void pushNamedAndRemoveUntil(BuildContext context, String routeName,
      {RoutePredicate predicate,Object arguments}) {
    if (predicate == null) {
      predicate = (route) => route.isFirst;
    }
    Navigator.of(context).pushNamedAndRemoveUntil(routeName, predicate,arguments: arguments);
  }

  ///回到指定页面
  static void popUntil(BuildContext context, String routeName) {
    Navigator.of(context).popUntil(ModalRoute.withName(routeName));
  }
}
